package leetcode.array;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * leetCode 16
 *  3Sum Closest
 * 最近三数之和
 * 翻译：最接近给定值的三数之和（审题，不一定是连在一起的三个数）
 * 思路：排序，左右指针

 */
public class Array16 {

    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        List<Integer> input = Arrays.stream(str.split(",")).map(i -> { return Integer.parseInt(i); }).collect(Collectors.toList());
        System.out.println(Arrays.toString(input.toArray()));
        Integer [] nums = input.toArray(new Integer[input.size()]);
        int target = Integer.parseInt(sc.next());
        new Array16().threeSumClosest(nums, target);
    }
    public int threeSumClosest(Integer[] nums, int target) {
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        int sum = 0;
        for(int k = 1;k < nums.length - 1;k++) {
            int i=0,j = nums.length - 1;
            while (i < j) {
                if(i == k){
                    i ++;
                    continue;
                }
                if (j == k){
                    j --;
                    continue;
                }
                int sub = target - nums[i] - nums[j] - nums[k];
                if (Math.abs(sub) < min) {
                    min = Math.abs(sub);
                    sum = nums[i] + nums[j] + nums[k];
                }
                if (sub > 0) {
                    i++;
                } else if (sub < 0) {
                    j--;
                } else {
                    return sum;
                }
            }
        }
        return sum;
    }
}
